package redis

import (
	"context"
	"fmt"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
)

var (
	Rsa        = rsaRedis{}
	redis      = g.Redis()
	expiration = g.Config().GetInt("crypto.expiration")
)

type rsaRedis struct{}

func (r *rsaRedis) getKey(id string) string {
	return fmt.Sprintf("rsa:%s", id)
}

// Set 将私钥添加进入redis
func (r *rsaRedis) Set(ctx context.Context, id string, value string) error {
	key := r.getKey(id)
	_, err := redis.Ctx(ctx).Do("SETEX", key, expiration, value)
	return err
}

// Get 获取id对应的私钥
func (r *rsaRedis) Get(ctx context.Context, id string) (string, error) {
	key := r.getKey(id)
	v, err := redis.Ctx(ctx).DoVar("GET", key)
	if err != nil {
		return "", err
	}
	if v == nil || v.IsNil() {
		return "", gerror.New("获取的值为空")
	}
	return v.String(), nil
}
